#include "mainwindow.h"
#include <QApplication>
#include <QScreen>
#include <QMessageBox>
#include <QTimer>
#include <QEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_centralWidget(nullptr)
    , m_mainLayout(nullptr)
    , m_inputGroup(nullptr)
    , m_inputLayout(nullptr)
    , m_nameEdit(nullptr)
    , m_ageEdit(nullptr)
    , m_phoneEdit(nullptr)
    , m_emailEdit(nullptr)
    , m_addressEdit(nullptr)
    , m_calculatorEdit(nullptr)
    , m_notesEdit(nullptr)
    , m_controlGroup(nullptr)
    , m_controlLayout(nullptr)
    , m_testButton(nullptr)
    , m_clearButton(nullptr)
    , m_modeCombo(nullptr)
    , m_autoShowCheck(nullptr)
    , m_statusLabel(nullptr)
    , m_keyboard(nullptr)
    , m_currentInput(nullptr)
    , m_autoShowKeyboard(true)
{
    setupUI();
    setupKeyboard();
    setupConnections();
    
    // 设置窗口属性
    setWindowTitle("触摸键盘演示程序 - BOMCO");
    setMinimumSize(800, 600);
    resize(1000, 700);
    
    // 居中显示
    QScreen *screen = QApplication::primaryScreen();
    QRect screenGeometry = screen->availableGeometry();
    int x = (screenGeometry.width() - width()) / 2;
    int y = (screenGeometry.height() - height()) / 2;
    move(x, y);
}

MainWindow::~MainWindow()
{
    if (m_keyboard) {
        m_keyboard->deleteLater();
    }
}

void MainWindow::setupUI()
{
    m_centralWidget = new QWidget(this);
    setCentralWidget(m_centralWidget);
    
    m_mainLayout = new QVBoxLayout(m_centralWidget);
    m_mainLayout->setSpacing(15);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 创建各个组件
    createInputFields();
    createControlPanel();
    
    // 状态标签
    m_statusLabel = new QLabel("准备就绪 - 点击输入框测试触摸键盘");
    m_statusLabel->setStyleSheet(
        "QLabel {"
        "    color: #666666;"
        "    font-size: 12px;"
        "    padding: 5px;"
        "    background-color: #f0f0f0;"
        "    border-radius: 3px;"
        "}"
    );
    
    m_mainLayout->addWidget(m_statusLabel);
}

void MainWindow::createInputFields()
{
    m_inputGroup = new QGroupBox("输入字段测试区域");
    m_inputGroup->setStyleSheet(
        "QGroupBox {"
        "    font-weight: bold;"
        "    font-size: 14px;"
        "    margin-top: 10px;"
        "    padding-top: 10px;"
        "}"
        "QGroupBox::title {"
        "    subcontrol-origin: margin;"
        "    left: 10px;"
        "    padding: 0 5px 0 5px;"
        "}"
    );
    
    m_inputLayout = new QGridLayout(m_inputGroup);
    m_inputLayout->setSpacing(15);
    m_inputLayout->setColumnStretch(1, 1);
    m_inputLayout->setColumnStretch(3, 1);
    
    // 创建输入字段
    int row = 0;
    
    // 姓名
    m_inputLayout->addWidget(new QLabel("姓名:"), row, 0);
    m_nameEdit = new QLineEdit();
    m_nameEdit->setPlaceholderText("请输入姓名");
    m_nameEdit->setMinimumHeight(35);
    m_inputLayout->addWidget(m_nameEdit, row, 1);
    
    // 年龄
    m_inputLayout->addWidget(new QLabel("年龄:"), row, 2);
    m_ageEdit = new QLineEdit();
    m_ageEdit->setPlaceholderText("请输入年龄");
    m_ageEdit->setMinimumHeight(35);
    m_inputLayout->addWidget(m_ageEdit, row, 3);
    
    row++;
    
    // 电话
    m_inputLayout->addWidget(new QLabel("电话:"), row, 0);
    m_phoneEdit = new QLineEdit();
    m_phoneEdit->setPlaceholderText("请输入电话号码");
    m_phoneEdit->setMinimumHeight(35);
    m_inputLayout->addWidget(m_phoneEdit, row, 1);
    
    // 邮箱
    m_inputLayout->addWidget(new QLabel("邮箱:"), row, 2);
    m_emailEdit = new QLineEdit();
    m_emailEdit->setPlaceholderText("请输入邮箱地址");
    m_emailEdit->setMinimumHeight(35);
    m_inputLayout->addWidget(m_emailEdit, row, 3);
    
    row++;
    
    // 地址
    m_inputLayout->addWidget(new QLabel("地址:"), row, 0);
    m_addressEdit = new QLineEdit();
    m_addressEdit->setPlaceholderText("请输入地址");
    m_addressEdit->setMinimumHeight(35);
    m_inputLayout->addWidget(m_addressEdit, row, 1, 1, 3);
    
    row++;
    
    // 计算器
    m_inputLayout->addWidget(new QLabel("计算器:"), row, 0);
    m_calculatorEdit = new QLineEdit();
    m_calculatorEdit->setPlaceholderText("数学表达式 (简洁模式测试)");
    m_calculatorEdit->setMinimumHeight(35);
    m_calculatorEdit->setStyleSheet("QLineEdit { background-color: #fff3cd; }");
    m_inputLayout->addWidget(m_calculatorEdit, row, 1, 1, 3);
    
    row++;
    
    // 备注
    m_inputLayout->addWidget(new QLabel("备注:"), row, 0, Qt::AlignTop);
    m_notesEdit = new QTextEdit();
    m_notesEdit->setPlaceholderText("请输入备注信息...");
    m_notesEdit->setMinimumHeight(80);
    m_notesEdit->setMaximumHeight(120);
    m_inputLayout->addWidget(m_notesEdit, row, 1, 1, 3);
    
    m_mainLayout->addWidget(m_inputGroup);
}

void MainWindow::createControlPanel()
{
    m_controlGroup = new QGroupBox("控制面板");
    m_controlGroup->setStyleSheet(
        "QGroupBox {"
        "    font-weight: bold;"
        "    font-size: 14px;"
        "    margin-top: 10px;"
        "    padding-top: 10px;"
        "}"
    );
    
    m_controlLayout = new QHBoxLayout(m_controlGroup);
    m_controlLayout->setSpacing(15);
    
    // 测试按钮
    m_testButton = new QPushButton("测试键盘");
    m_testButton->setMinimumHeight(40);
    m_testButton->setStyleSheet(
        "QPushButton {"
        "    background-color: #007bff;"
        "    color: white;"
        "    border: none;"
        "    border-radius: 5px;"
        "    font-weight: bold;"
        "    padding: 8px 16px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #0056b3;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #004085;"
        "}"
    );
    
    // 清除按钮
    m_clearButton = new QPushButton("清除所有");
    m_clearButton->setMinimumHeight(40);
    m_clearButton->setStyleSheet(
        "QPushButton {"
        "    background-color: #dc3545;"
        "    color: white;"
        "    border: none;"
        "    border-radius: 5px;"
        "    font-weight: bold;"
        "    padding: 8px 16px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #c82333;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #bd2130;"
        "}"
    );
    
    // 模式选择
    QLabel *modeLabel = new QLabel("键盘模式:");
    m_modeCombo = new QComboBox();
    m_modeCombo->addItem("简洁模式", static_cast<int>(TouchKeyboard::SimpleMode));
    m_modeCombo->addItem("全键盘模式", static_cast<int>(TouchKeyboard::FullMode));
    m_modeCombo->setMinimumHeight(35);
    
    // 自动显示选项
    m_autoShowCheck = new QCheckBox("点击输入框自动显示键盘");
    m_autoShowCheck->setChecked(m_autoShowKeyboard);
    
    m_controlLayout->addWidget(m_testButton);
    m_controlLayout->addWidget(m_clearButton);
    m_controlLayout->addStretch();
    m_controlLayout->addWidget(modeLabel);
    m_controlLayout->addWidget(m_modeCombo);
    m_controlLayout->addStretch();
    m_controlLayout->addWidget(m_autoShowCheck);
    
    m_mainLayout->addWidget(m_controlGroup);
}

void MainWindow::setupKeyboard()
{
    m_keyboard = new SimpleKeyboard();
    
    // 确保键盘模式正确初始化
    m_keyboard->setMode(TouchKeyboard::SimpleMode);
    
    // 连接键盘信号
    connect(m_keyboard, &TouchKeyboard::modeChanged, 
            this, &MainWindow::onKeyboardModeChanged);
    connect(m_keyboard, &TouchKeyboard::keyboardHidden, 
            this, &MainWindow::onKeyboardHidden);
}

void MainWindow::setupConnections()
{
    // 输入框焦点事件
    QList<QLineEdit*> lineEdits = {m_nameEdit, m_ageEdit, m_phoneEdit, 
                                   m_emailEdit, m_addressEdit, m_calculatorEdit};
    
    for (QLineEdit *edit : lineEdits) {
        connect(edit, &QLineEdit::customContextMenuRequested, this, &MainWindow::onInputFocused);
        // 使用事件过滤器来捕获焦点事件
        edit->installEventFilter(this);
    }
    
    // 为QTextEdit（备注输入域）也安装事件过滤器
    if (m_notesEdit) {
        m_notesEdit->installEventFilter(this);
    }
    
    // 控制按钮
    connect(m_testButton, &QPushButton::clicked, this, &MainWindow::onTestButtonClicked);
    connect(m_clearButton, &QPushButton::clicked, this, &MainWindow::onClearAllClicked);
    
    // 模式选择
    connect(m_modeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            [this](int index) {
                TouchKeyboard::KeyboardMode mode = 
                    static_cast<TouchKeyboard::KeyboardMode>(m_modeCombo->itemData(index).toInt());
                m_keyboard->setMode(mode);
            });
    
    // 自动显示选项
    connect(m_autoShowCheck, &QCheckBox::toggled, 
            [this](bool checked) {
                m_autoShowKeyboard = checked;
            });
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::FocusIn) {
        // 处理QLineEdit和QTextEdit的焦点事件
        QLineEdit *lineEdit = qobject_cast<QLineEdit*>(obj);
        QTextEdit *textEdit = qobject_cast<QTextEdit*>(obj);
        
        if ((lineEdit || textEdit) && m_autoShowKeyboard) {
            // 避免焦点循环：如果键盘已经显示且目标输入框相同，则不重复显示
            if (m_keyboard->isVisible() && 
                ((m_keyboard->getTargetInput() == lineEdit) || 
                 (m_keyboard->getTargetTextEdit() == textEdit))) {
                // 即使是相同输入框，也要确保光标位置正确
                QTimer::singleShot(0, [lineEdit, textEdit]() {
                    if (lineEdit) {
                        lineEdit->setCursorPosition(lineEdit->text().length());
                    } else if (textEdit) {
                        textEdit->moveCursor(QTextCursor::End);
                    }
                });
                return QMainWindow::eventFilter(obj, event);
            }
            
            // 为计算器输入框设置简洁模式
            if (lineEdit == m_calculatorEdit) {
                m_keyboard->setMode(TouchKeyboard::SimpleMode);
                m_modeCombo->setCurrentIndex(0);
            }
            
            // 显示键盘
            if (lineEdit) {
                m_keyboard->showKeyboard(lineEdit);
            } else if (textEdit) {
                m_keyboard->showKeyboard(textEdit);
            }
            
            // 确保输入框保持焦点（在键盘显示后设置）
            QTimer::singleShot(100, [lineEdit, textEdit]() {
                if (lineEdit) {
                    lineEdit->setFocus();
                    lineEdit->setCursorPosition(lineEdit->text().length()); // 将光标移到末尾
                } else if (textEdit) {
                    textEdit->setFocus();
                    textEdit->moveCursor(QTextCursor::End); // 将光标移到末尾
                }
            });
            
            QString placeholderText = lineEdit ? lineEdit->placeholderText() : "备注输入域";
            m_statusLabel->setText(QString("键盘已显示 - 当前输入: %1").arg(placeholderText));
        }
    } else if (event->type() == QEvent::FocusOut) {
        // 处理焦点丢失事件
        QLineEdit *lineEdit = qobject_cast<QLineEdit*>(obj);
        QTextEdit *textEdit = qobject_cast<QTextEdit*>(obj);
        
        if ((lineEdit && lineEdit == m_currentInput) || (textEdit && m_keyboard->getTargetTextEdit() == textEdit)) {
            // 如果当前输入框失去焦点，检查是否是因为键盘操作导致的
            // 给一点延迟来判断是否是临时的焦点切换
            QTimer::singleShot(100, [this, lineEdit, textEdit]() {
                // 如果键盘仍然显示且目标输入框仍然是这个输入框，则恢复焦点
                if (m_keyboard->isVisible()) {
                    if ((lineEdit && m_keyboard->getTargetInput() == lineEdit) || 
                        (textEdit && m_keyboard->getTargetTextEdit() == textEdit)) {
                        QTimer::singleShot(0, [lineEdit, textEdit]() {
                            if (lineEdit) {
                                lineEdit->setFocus();
                                lineEdit->setCursorPosition(lineEdit->text().length());
                            } else if (textEdit) {
                                textEdit->setFocus();
                                textEdit->moveCursor(QTextCursor::End);
                            }
                        });
                    }
                }
            });
        }
    } else if (event->type() == QEvent::MouseButtonPress) {
        // 处理鼠标点击事件，确保点击输入框时能正确获取焦点
        QLineEdit *lineEdit = qobject_cast<QLineEdit*>(obj);
        QTextEdit *textEdit = qobject_cast<QTextEdit*>(obj);
        
        if ((lineEdit || textEdit) && m_autoShowKeyboard) {
            // 为计算器输入框设置简洁模式
            if (lineEdit == m_calculatorEdit) {
                m_keyboard->setMode(TouchKeyboard::SimpleMode);
                m_modeCombo->setCurrentIndex(0);
            }
            
            // 显示键盘
            if (lineEdit) {
                m_keyboard->showKeyboard(lineEdit);
            } else if (textEdit) {
                m_keyboard->showKeyboard(textEdit);
            }
            
            // 确保输入框保持焦点
            QTimer::singleShot(150, [lineEdit, textEdit]() {
                if (lineEdit) {
                    lineEdit->setFocus();
                    lineEdit->setCursorPosition(lineEdit->text().length()); // 将光标移到末尾
                } else if (textEdit) {
                    textEdit->setFocus();
                    textEdit->moveCursor(QTextCursor::End); // 将光标移到末尾
                }
            });
            
            QString placeholderText = lineEdit ? lineEdit->placeholderText() : "备注输入域";
            m_statusLabel->setText(QString("键盘已显示 - 当前输入: %1").arg(placeholderText));
            return true; // 处理了事件，不需要传递给父类
        }
    }
    
    return QMainWindow::eventFilter(obj, event);
}

void MainWindow::onInputFocused()
{
    QLineEdit *lineEdit = qobject_cast<QLineEdit*>(sender());
    if (lineEdit) {
        m_currentInput = lineEdit;
        m_keyboard->showKeyboard(lineEdit);
        m_statusLabel->setText(QString("键盘已显示 - 当前输入: %1").arg(lineEdit->placeholderText()));
    }
}

void MainWindow::onKeyboardModeChanged(TouchKeyboard::KeyboardMode mode)
{
    QString modeText = (mode == TouchKeyboard::SimpleMode) ? "简洁模式" : "全键盘模式";
    m_statusLabel->setText(QString("键盘模式已切换到: %1").arg(modeText));
    
    // 同步组合框选择
    int index = (mode == TouchKeyboard::SimpleMode) ? 0 : 1;
    m_modeCombo->setCurrentIndex(index);
}

void MainWindow::onKeyboardHidden()
{
    m_statusLabel->setText("键盘已隐藏");
    m_currentInput = nullptr;
}

void MainWindow::onTestButtonClicked()
{
    if (m_keyboard->isVisible()) {
        m_keyboard->hideKeyboard();
    } else {
        // 显示键盘，定位到计算器输入框
        m_calculatorEdit->setFocus();
        m_keyboard->setMode(TouchKeyboard::SimpleMode);
        m_keyboard->showKeyboard(m_calculatorEdit);
        m_statusLabel->setText("测试模式 - 键盘已显示在计算器输入框");
    }
}

void MainWindow::onClearAllClicked()
{
    // 清除所有输入框
    m_nameEdit->clear();
    m_ageEdit->clear();
    m_phoneEdit->clear();
    m_emailEdit->clear();
    m_addressEdit->clear();
    m_calculatorEdit->clear();
    m_notesEdit->clear();
    
    // 隐藏键盘
    if (m_keyboard->isVisible()) {
        m_keyboard->hideKeyboard();
    }
    
    m_statusLabel->setText("所有输入已清除");
}
